<template>
	<l-page :page.sync="queryParams.pageNum" :page-size.sync="queryParams.pageSize" :total="total" @getList="getList">
		<el-form ref="queryForm" slot="header" :inline="true" :model="queryParams" label-position="left" label-width="75px">
			<el-form-item label="素材名称:" prop="title">
				<el-input v-model.trim="queryParams.title" clearable placeholder="请输入素材名称" />
			</el-form-item>

			<el-form-item label="素材状态:" prop="state">
				<el-select v-model="queryParams.state" placeholder="请选择状态">
					<el-option :value="null" label="全部" />
					<el-option label="上架" value="1" />
					<el-option label="下架" value="0" />
				</el-select>
			</el-form-item>

			<start-end-time ref="child" :get-time="getTime" title="创建时间:"></start-end-time>
		</el-form>

		<template slot="options">
			<l-search @search="handleQuery" @refresh="resetQuery" />
			<el-button v-hasPermi="['system:material:add']" type="primary" icon="el-icon-plus" @click="handleAdd">新增素材 </el-button>
		</template>
		<el-table v-loading="loading" :data="materialList" stripe @selection-change="handleSelectionChange">
			<el-table-column :formatter="emptyToString" align="center" label="序号" type="index" width="50" />
			<el-table-column :formatter="emptyToString" align="center" label="素材名称" prop="title" min-width="156" />
			<el-table-column :formatter="emptyToString" align="center" label="素材内容" min-width="200" prop="context" show-overflow-tooltip>
				<template slot-scope="scope">
					<span>{{ scope.row.context }}</span>
				</template>
			</el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="朋友圈素材图片" min-width="160">
				<template slot-scope="scope">
					<el-image v-if="scope.row.picUrl" :preview-src-list="[scope.row.picUrl.split(',')[0]]" :src="scope.row.picUrl.split(',')[0]" style="width: 48px; height: 48px"> </el-image>
					<div v-else>-</div>
				</template>
			</el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="状态" prop="state" min-width="156">
				<template slot-scope="scope">
					<el-switch v-model="scope.row.state" :active-value="1" :inactive-value="0" active-text="上架" class="switch" inactive-text="下架" @change="handleUpdateStatus(scope.row)"></el-switch>
				</template>
			</el-table-column>
			<l-table-column type="sortOrder" label="展示顺序" :min-width="156" @reSortOrderReduce="reSortOrderReduce($event.id)" @reSortOrderPlus="reSortOrderPlus($event.id)"></l-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="置顶" prop="top" min-width="156">
				<template slot-scope="scope">
					<el-switch v-model="scope.row.top" :active-value="1" :inactive-value="0" active-text="是" class="switch" inactive-text="否" @change="handleUpdateTop(scope.row)"></el-switch>
				</template>
			</el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="创建时间" min-width="156" prop="createTime">
				<template slot-scope="scope">
					<div class="w-full flex flex-col items-center">
						<span>{{ dayjs(scope.row.createTime).format('YYYY-MM-DD') }}</span>
						<span>{{ dayjs(scope.row.createTime).format('HH:mm:ss') }}</span>
					</div>
				</template>
			</el-table-column>
			<el-table-column :formatter="emptyToString" :width="tableAction" align="center" fixed="right" header-align="center" label="操作">
				<template slot-scope="scope">
					<div class="table-action flex justify-center">
						<el-button v-hasPermi="['system:material:edit']" type="primary" @click="handleUpdate(scope.row)">编辑 </el-button>
						<el-button v-hasPermi="['system:material:remove']" type="danger" @click="handleDelete(scope.row, scope)">删除 </el-button>
					</div>
				</template>
			</el-table-column>
		</el-table>

		<!-- 添加或编辑朋友圈素材对话框 -->
		<l-dialog v-model="open" :loading.sync="formLoading" :title="title" width="642px" @close="cancel" @formClose="cancel" @formSubmit="submitForm">
			<el-form ref="form" :model="form" :rules="rules" label-position="left" label-width="70px">
				<el-form-item label="名称：" prop="title">
					<el-input v-model.trim="form.title" class="!w-[463px] !max-w-[463px]" maxlength="20" placeholder="请输入名称" show-word-limit />
				</el-form-item>
				<el-form-item label="内容：" prop="context">
					<el-input v-model.trim="form.context" :rows="12" class="!w-[463px] !max-w-[463px]" maxlength="700" placeholder="请输入内容" show-word-limit type="textarea" />
				</el-form-item>
				<el-form-item prop="picUrlList">
					<l-upload-image v-model="picUrlList" :limit="9" height="117px" width="117px">
						<div class="flex flex-col">
							<i class="el-icon-plus mb-[6px] text-[30px]"></i>
							<el-tooltip effect="dark" placement="top">
								<div slot="content">图片大小建议为4M内，支持图片类 <br />型jpj,png，最多上传9张，最少1张。</div>

								<div class="text-[14px] text-[#cccccc] cursor-pointer">上传图片 <i class="el-icon-question"></i></div>
							</el-tooltip>
						</div>
					</l-upload-image>
				</el-form-item>
			</el-form>
		</l-dialog>
	</l-page>
</template>

<script>
import { addMaterial, delMaterial, exportMaterial, getMaterial, listMaterial, updateMaterial } from '@/api/mall/material';
import startEndTime from '@/components/StartEndTime';
import tableMixins from '@/mixins/table';
import TemplateZone from '@/views/mall/logistics/templateZone';

export default {
	name: 'Material',
	components: {
		TemplateZone,
		startEndTime,
	},
	mixins: [tableMixins],
	data() {
		return {
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 朋友圈素材表格数据
			materialList: [],
			// 弹出层标题
			title: '',
			// 是否显示弹出层
			open: false,
			// 搜索参数
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				title: null,
				picUrl: null,
				context: null,
				state: null,
				userId: null,
				tenantId: null,
				time: [],
			},
			// 表单参数
			form: {},
			formLoading: false,
			picUrlList: [],
			// 表单校验
			rules: {
				title: [{ required: true, message: '请填写名称', trigger: 'blur' }],
				context: [{ required: true, message: '请填写内容', trigger: 'blur' }],
			},
		};
	},
	created() {
		console.log(this.form.picUrl);
		this.getList();
	},
	methods: {
		handleUpdateStatus(row) {
			updateMaterial({ id: row.id, state: row.state })
				.then(() => {
					this.$message.success(row.state ? '上架成功' : '下架成功');
					this.getList();
				})
				.catch(() => {
					row.status = !row.status;
				});
		},
		handleUpdateTop(row) {
			updateMaterial({ id: row.id, top: row.top })
				.then(() => {
					this.$message.success(row.state ? '上架成功' : '下架成功');
					this.getList();
				})
				.catch(() => {
					row.status = !row.status;
				});
		},
		/** 搜索朋友圈素材列表 */
		getList() {
			this.loading = true;
			if (this.queryParams.time) {
				this.queryParams.startTime = this.queryParams.time[0];
				this.queryParams.endTime = this.queryParams.time[1];
			}
			listMaterial(this.queryParams).then((response) => {
				this.materialList = response.data.records;
				this.total = response.data.total;
				this.loading = false;
				this.setActionWidth();
			});
		},
		// 取消按钮
		cancel() {
			this.open = false;
			this.reset();
		},
		reSortOrderReduce(id) {
			this.$request.post('/system/material/reSortOrderReduce', { id }).then(() => {
				this.getList();
			});
		},
		reSortOrderPlus(id) {
			this.$request.post('/system/material/reSortOrderPlus', { id }).then(() => {
				this.getList();
			});
		},
		// 表单重置
		reset() {
			this.picUrlList = [];
			this.form = {
				id: null,
				title: null,
				picUrl: null,
				context: null,
				state: null,
				userId: null,
				delFlag: null,
				createBy: null,
				createTime: null,
				updateBy: null,
				updateTime: null,
				tenantId: null,
			};
			this.resetForm('form');
		},
		//获取子组件startendtime时间数据
		getTime(startTime, endTime) {
			this.$set(this.queryParams.time, 0, startTime);
			this.$set(this.queryParams.time, 1, endTime);
		},
		/** 搜索按钮操作 */
		handleQuery() {
			console.log(this.queryParams.time);
			this.queryParams.pageNum = 1;
			this.getList();
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.$refs.child.resetTime();
			this.resetForm('queryForm');
			this.handleQuery();
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map((item) => item.id);
			this.single = selection.length !== 1;
			this.multiple = !selection.length;
		},
		/** 新增按钮操作 */
		handleAdd() {
			this.reset();
			this.open = true;
			this.title = '添加朋友圈素材';
		},
		/** 编辑按钮操作 */
		handleUpdate(row) {
			this.reset();
			const id = row.id || this.ids;
			getMaterial(id).then((response) => {
				this.form = response.data;
				this.picUrlList = response.data.picUrl.split(',');
				this.open = true;
				this.title = '编辑朋友圈素材';
			});
		},
		/** 提交按钮 */
		submitForm() {
			this.$refs['form'].validate((valid) => {
				if (valid) {
					this.formLoading = true;
					if (!this.picUrlList.length) {
						this.$message.error('请添加图片');
						this.formLoading = false;
						return;
					}
					this.form.picUrl = this.picUrlList.toString(',');
					if (this.form.id != null) {
						updateMaterial(this.form)
							.then(() => {
								this.msgSuccess('编辑成功');
								this.open = false;
								this.getList();
							})
							.finally(() => {
								this.formLoading = false;
							});
					} else {
						this.form.state = 0;
						addMaterial(this.form)
							.then(() => {
								this.msgSuccess('新增成功');
								this.open = false;
								this.getList();
							})
							.finally(() => {
								this.formLoading = false;
							});
					}
				} else {
					this.formLoading = false;
				}
			});
		},
		/** 删除按钮操作 */
		handleDelete(row) {
			const ids = row.id || this.ids;
			this.$dialogRemove('确定删除该朋友圈素材吗？').then((res) => {
				delMaterial({ id: [ids] })
					.then(() => {
						this.$message({
							type: 'success',
							message: '删除成功!',
						});
						setTimeout(() => {
							this.getList();
							res.hide();
						}, 100);
					})
					.finally(() => {
						res.loading(false);
					});
			});
		},
		/** 导出按钮操作 */
		handleExport() {
			const queryParams = this.queryParams;
			this.$confirm('是否确认导出所有朋友圈素材数据项?', '警告', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(function () {
					return exportMaterial(queryParams);
				})
				.then((response) => {
					this.download(response.msg);
				});
		},
	},
};
</script>
<style lang="scss" scoped>
::v-deep.pagination-container {
	background: none;
}
</style>
